<template>
  <div class="h-full">
    <!-- 添加扫描器视图容器 -->
    <div v-show="showQrcodeView" class="w-full h-full flex relative">
      <video id="interactive" class="w-full h-full object-cover" />
      <!-- 二维码扫描覆盖层组件 -->
      <QrScannerOverlay @close="stopQrcodeSanner" />
    </div>

    <!-- <template v-show="!showQrcodeView"> -->
    <deviceInfoView
      v-if="deviceCode"
      :deviceCode="deviceCode"
      :deviceInfo="deviceInfo"
      @clickChangeBtn="showChangeBindDialog = true"
      @clickUnbindBtn="onClickUnBindBtn"
    />
    <emptyDeviceInfoView @clickBindBtn="showBindDialog = true" v-else />

    <div class="py-20 px-4" v-if="enableTestStart">
      <van-field
        class="mb-4 shadow"
        placeholder="请输入scheduleId"
        border
        v-model="scheduleId"
      ></van-field>
      <van-button size="large" color="#436BFF" plain round @click="onClickStart"
        >启动录制</van-button
      >
    </div>
    <!-- </template> -->
  </div>

  <van-dialog
    v-model:show="showBindDialog"
    title="添加工牌设备"
    show-cancel-button
    :confirm-button-disabled="SN_Code.length === 0"
    @confirm="onConfirmBind"
  >
    <bindDeviceView
      v-if="showBindDialog"
      v-model:text="SN_Code"
      @onScan="onStartScanning"
      :querySearchName="querySearchName"
      :handleSelectSuggestions="handleSelectSuggestions"
    />
  </van-dialog>

  <van-dialog
    v-model:show="showChangeBindDialog"
    title="更换工牌设备"
    show-cancel-button
    :confirm-button-disabled="SN_Code.length === 0"
    @confirm="onConfirmBind"
  >
    <bindDeviceView
      v-if="showChangeBindDialog"
      v-model:text="SN_Code"
      @onScan="onStartScanning"
      des="更换设备将解绑当前设备"
      :querySearchName="querySearchName"
      :handleSelectSuggestions="handleSelectSuggestions"
    />
  </van-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from "vue";
import bindDeviceView from "./components/bindDeviceView.vue";
import deviceInfoView from "./components/deviceInfoView.vue";
import emptyDeviceInfoView from "./components/emptyDeviceInfoView.vue";
import QrScannerOverlay from "@/components/QrScannerOverlay.vue";
import { bindDeviceAPI, unBindDeviceAPI, getDeviceInfoAPI } from "@/services/badge";
import { HAS_BEEN_BIND_CODE, SUCCESS_CODE } from "@/services/apiErrorCode";
import { BindDeviceParam, BadgeDeviceInfo } from "@/services/badge/type";
import {
  closeToast,
  showLoadingToast,
  showToast,
  showConfirmDialog,
  showDialog,
} from "vant";
import { useCommonStore } from "@/store";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
import "vant/lib/index.css";
import { useScanner } from "@/composables/useScanner";

const SN_Code = ref("");
const showBindDialog = ref(false);
const showChangeBindDialog = ref(false);
const commonStore = useCommonStore();
const route = useRoute();
const router = useRouter();

const { startScanning, stopScanning } = useScanner(onQrCodeResult);

onMounted(async () => {
  await reloadUserInfo();
  if (deviceCode.value) {
    checkDeviceInfo();
  }
});

// 点击解除绑定
function onClickUnBindBtn() {
  const messagesArr = [
    "您确定要解绑此工牌设备吗？",
    "序列号" + deviceCode.value,
    "解绑后需要重新绑定才能使用。",
  ];

  showConfirmDialog({
    title: "确认解绑设备",
    message: messagesArr.join("\n"),
  }).then(() => {
    doUnBindAction();
  });
}

async function doUnBindAction() {
  showLoadingToast("正在解绑");
  await unBindDeviceAPI();
  await reloadUserInfo();
  closeToast();
}

function onConfirmBind() {
  bindBadgeApi();
}

// 绑定工牌api
async function bindBadgeApi(forceBind = false) {
  if (SN_Code.value.length === 0) {
    showToast("SN码为空!");
    return;
  }
  const bindParam = new BindDeviceParam();
  bindParam.code = SN_Code.value;
  bindParam.forceBind = forceBind;
  const res = await bindDeviceAPI(bindParam);
  const { code, message } = res;
  if (HAS_BEEN_BIND_CODE === code) {
    // 已经被其他用户绑定
    showForceAlert();
    return;
  }
  if (SUCCESS_CODE !== code) {
    showToast(message);
    clearInput();
    return;
  }
  saveCodeCache(SN_Code.value);
  await reloadUserInfo();
  checkDeviceInfo();
  showToast("绑定成功");
  clearInput();
}

const SY_CODE_KEY = "SY_CODE_KEY";
function loadCodeCache() {
  return JSON.parse(localStorage.getItem(SY_CODE_KEY) || "[]");
}

function saveCodeCache(code: string) {
  let array = loadCodeCache() || [];
  array.push(code);
  localStorage.setItem(SY_CODE_KEY, JSON.stringify(array));
}

async function querySearchName(query: string, cb: any) {
  if (query.length === 0) {
    cb([]);
    return;
  }
  let arr = loadCodeCache() || [];
  console.log("querySearchName:", query, arr);
  let result = arr.filter((v) => v.indexOf(query) > -1);
  console.log("result: ", result);
  result = result.map((v) => {
    return { value: v };
  });
  cb(result);
}

function handleSelectSuggestions(v) {
  console.log("handleSelectSuggestions: ", v);
}

function clearInput() {
  SN_Code.value = "";
}

const scheduleId = ref("");
async function onClickStart() {
  await router.push({
    path: "badge/record",
    query: {
      st: dayjs().format("YYYYMMDDHHmmss"),
    },
  });
}

function showForceAlert() {
  showConfirmDialog({
    title: "提示",
    message: "设备已绑定其他用户,是否强制绑定?",
  })
    .then(() => {
      // on confirm
      bindBadgeApi(true);
    })
    .catch(() => {
      // on cancel
    });
}

async function reloadUserInfo() {
  await (commonStore as any).getUserInfoAction();
  try {
    window.flutter_inappwebview.callHandler("reloadUserInfo");
  } catch (e) {
    console.log("非app端执行，无法与原生进行通讯");
  }
}

const enableTestStart = computed(() => {
  return deviceCode.value && route.query.start;
});
const userInfo = computed(() => commonStore.userInfo);
const deviceCode = computed(() => (userInfo.value as any)?.audioDeviceCode);
const deviceInfo = ref<BadgeDeviceInfo | null>(null);

async function getDeviceInfo() {
  const data = await getDeviceInfoAPI(deviceCode.value);
  console.log("regetDeviceInfos: ", data);
  if (data.length === 0) {
    return;
  }
  deviceInfo.value = data[0];
}

let intervalTimer: any = null;
async function checkDeviceInfo() {
  if (intervalTimer) {
    clearInterval(intervalTimer);
  }
  if (deviceCode.value) {
    getDeviceInfo();
  }
  intervalTimer = setInterval(async () => {
    await reloadUserInfo();
    if (deviceCode.value) {
      getDeviceInfo();
    }
  }, 60000);
}

const showQrcodeView = ref(false);
async function onStartScanning() {
  showToast("开始扫描");
  showBindDialog.value = false;
  showQrcodeView.value = true;
  startScanning("interactive");
}

function onQrCodeResult(result: string) {
  if (result.length === 0) {
    return;
  }
  showDialog({
    title: `识别成功`,
    message: "SN码: " + result,
    confirmButtonText: "直接绑定",
  }).then(() => {
    SN_Code.value = result;
    stopQrcodeSanner();
    onConfirmBind();
  });
}

function stopQrcodeSanner() {
  showQrcodeView.value = false;
  try {
    stopScanning();
  } catch (e) {
    console.log("stopQrcodeSanner error: ", e);
  }
}

onUnmounted(() => {
  stopScanning();
});
</script>

<style lang="less" scoped>
#interactive.viewport {
  width: 640px;
  height: 480px;
  canvas,
  video {
    float: left;
    width: 640px;
    height: 480px;
  }
  canvas.drawingBuffer,
  video.drawingBuffer {
    margin-left: -640px;
  }
}
</style>
